//
//  String+YCExtension.swift
//  yc-basic-common
//
//  Created by 董鹏 on 2022/1/19.
//

import UIKit
import SwiftDate

public extension String {
    
    /**
     * 时间格式转换
     * 将20010203 转化为 2001/02/03
     */
    func changeTimeDisplayFormatWithOriginalTime(dateFormat: String? = "yyyy/MM/dd") -> String?{
        let format = DateFormatter.init()
        format.dateFormat = "yyyyMMdd"
        guard let date = format.date(from: self) else { return "" }
        format.dateFormat = dateFormat
        return format.string(from: date)
    }
    /**
    * 时间格式转换
    * 将2020-07-13T16:34:05. 877000+08:00 转化为 2020-07-13 16:34:05
    */
    func changeTimeStandard() -> String?{
        let timeAndtimeZoneArr = self.components(separatedBy: ".")
        if timeAndtimeZoneArr.count < 2{
            return nil
        }
        let timeArr = timeAndtimeZoneArr[0].components(separatedBy: "T")
        if timeArr.count < 2{
            return nil
        }
        return "\(timeArr[0]) \(timeArr[1])"
    }
    /**
    * 时间格式转换
    * 指定时间格式
    */
    func changeTimeStandard(_ toFormat:String) -> String?{
        if let timeStr = self.changeTimeStandard(){
            let normalDate = timeStr.toDate()
            return normalDate?.toFormat(toFormat)
        }
        return nil
    }
    /**
     * 时间格式 今天 昨天 周几
     * 时间格式为 今天 + Format
     * 例如 toFormat 为 HH:mm
     * 则为 今天 10:20
     */
    func specificChangeTimeStandard(_ toFormat:String) -> String?{
        if let timeStr = self.changeTimeStandard(), let normalDate = timeStr.toDate(){
            let time = normalDate.toFormat(toFormat)
            // 是否是今天
            if normalDate.isToday{
                return time
            }
            // 是否是 昨天
            if normalDate.isYesterday{
                return "昨天 \(time)"
            }
            // 判断是否是本周
            if normalDate.year == Date().year && normalDate.month == Date().month && normalDate.weekOfYear == Date().weekOfYear{
                return normalDate.weekdayName(.default) + "\(time)"
            }
            // 其他 yyyy-MM-dd HH:mm
            return self.changeTimeStandard("yyyy-MM-dd HH:mm")
        }
        return nil
    }
    
    /**
     * base64字符转换为图片
     * 参数 base64字符
     * 返回值 图片
     */
    func base64StrToimage() -> UIImage?{
        
        guard let imageData = Data(base64Encoded: self) else {return nil}

        // 将Data转化成图片
        let image = UIImage(data: imageData)

        return image
    }
    //获取拼音首字母（大写字母）
    func findFirstLetterFromString() -> String? {
        //转变成可变字符串
        let mutableString = NSMutableString(string: self)

        //将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil,      kCFStringTransformToLatin, false)

        //去掉声调
        let pinyinString = mutableString.folding(options:          String.CompareOptions.diacriticInsensitive, locale:   NSLocale.current)

        //将拼音首字母换成大写
        let strPinYin = pinyinString.uppercased()

        //截取大写首字母
        if strPinYin.isEmpty {
            return nil
        }
        let firstString = strPinYin.prefix(1)
        // 判断首字母是否为大写
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        
        return predA.evaluate(with: firstString) ? "\(firstString)" : "#"
    }
    
    /// 判断是不是Emoji
    ///
    /// - Returns: true false
    func containsEmoji() -> Bool{
        for scalar in unicodeScalars {
            switch scalar.value {
            case 0x1F600...0x1F64F,
                 0x1F300...0x1F5FF,
                 0x1F680...0x1F6FF,
                 0x2600...0x26FF,
                 0x2700...0x27BF,
                 0xFE00...0xFE0F:
                return true
            default:
                continue
            }
        }
        
        return false
    }
    
    /// 判断是不是Emoji
    ///
    /// - Returns: true false
    func hasEmoji() -> Bool {
        
        let pattern = "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"
        let pred = NSPredicate(format: "SELF MATCHES %@",pattern)
        return pred.evaluate(with: self)
    }
    
    /// 然后是去除字符串中的表情
    ///
    /// - Parameter text: text
    func disable_emoji(text : NSString) -> String {
        do {
            let regex = try NSRegularExpression(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: NSRegularExpression.Options.caseInsensitive)
            
            let modifiedString = regex.stringByReplacingMatches(in: text as String, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, text.length), withTemplate: "")
            
            return modifiedString
        } catch {
            print(error)
        }
        return ""
    }
}
